package com.ruoyi.teacher.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.teacher.domain.TTeacher;
import com.ruoyi.teacher.dto.RosteringDto;
import com.ruoyi.teacher.mapper.TTeacherMapper;
import com.ruoyi.teacher.service.ITTeacherService;
import com.ruoyi.teacher.teacherUtils.RosterUtil;
import com.ruoyi.teacher.teacherUtils.TimeUtil;
import com.ruoyi.teacher.vo.GroupVo;
import com.ruoyi.teacher.vo.RosteringVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.teacher.mapper.TTeacherRosteringMapper;
import com.ruoyi.teacher.domain.TTeacherRostering;
import com.ruoyi.teacher.service.ITTeacherRosteringService;

/**
 * 老师排班Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-12-26
 */
@Service
public class TTeacherRosteringServiceImpl implements ITTeacherRosteringService
{
    @Autowired
    private TTeacherRosteringMapper tTeacherRosteringMapper;

    @Value("${dingtalk.roster.appKey}")
    private String appKey;

    @Value("${dingtalk.roster.appSecret}")
    private String appSecret;

    @Value("${dingtalk.roster.appKey}")
    private String opUserId;

    @Autowired
    private TTeacherMapper teacherMapper;

    /**
     * 查询老师排班
     * 
     * @param id 老师排班主键
     * @return 老师排班
     */
    @Override
    public TTeacherRostering selectTTeacherRosteringById(Long id)
    {
        return tTeacherRosteringMapper.selectTTeacherRosteringById(id);
    }

    /**
     * 查询老师排班列表
     * 
     * @param tTeacherRostering 老师排班
     * @return 老师排班
     */
    @Override
    public List<TTeacherRostering> selectTTeacherRosteringList(TTeacherRostering tTeacherRostering)
    {
        return tTeacherRosteringMapper.selectTTeacherRosteringList(tTeacherRostering);
    }

    /**
     * 新增老师排班
     * 
     * @param tTeacherRostering 老师排班
     * @return 结果
     */
    @Override
    public int insertTTeacherRostering(TTeacherRostering tTeacherRostering)
    {
        return tTeacherRosteringMapper.insertTTeacherRostering(tTeacherRostering);
    }

    /**
     * 修改老师排班
     * 
     * @param tTeacherRostering 老师排班
     * @return 结果
     */
    @Override
    public int updateTTeacherRostering(TTeacherRostering tTeacherRostering)
    {
        return tTeacherRosteringMapper.updateTTeacherRostering(tTeacherRostering);
    }

    /**
     * 批量删除老师排班
     * 
     * @param ids 需要删除的老师排班主键
     * @return 结果
     */
    @Override
    public int deleteTTeacherRosteringByIds(Long[] ids)
    {
        return tTeacherRosteringMapper.deleteTTeacherRosteringByIds(ids);
    }

    /**
     * 删除老师排班信息
     * 
     * @param id 老师排班主键
     * @return 结果
     */
    @Override
    public int deleteTTeacherRosteringById(Long id)
    {
        return tTeacherRosteringMapper.deleteTTeacherRosteringById(id);
    }

    /**
     * 从钉钉那里同步老师排班信息
     * @return
     */
    @Override
    public String updateRoster() {
        String accessToken = RosterUtil.getAccessToken();
        String rosterInfo = RosterUtil.getRosterInfo();
        String result = JSONObject.parseObject(rosterInfo).getString("result");
        List<TTeacherRostering> tTeacherRosterings = JSONObject.parseArray(result, TTeacherRostering.class);
        for (TTeacherRostering teacherRostering : tTeacherRosterings) {
            System.out.println(teacherRostering);
            tTeacherRosteringMapper.insertTTeacherRostering(teacherRostering);
        }
        return "同步到数据库成功！";
    }

    /**
     * 排班
     * @param rosteringDto
     * @return
     */
    @Override
    public String rostering(RosteringDto rosteringDto) {

        System.out.println(rosteringDto);
        String time = rosteringDto.getTime();
        Long group_id = rosteringDto.getGroup_id();
        Long shift_id = rosteringDto.getShift_id();

        if (group_id == null || shift_id == null) {
            return "排班错误，请联系管理员！";
        }

        // 获取登录用户id
        Long userId = SecurityUtils.getUserId();

        //设置时间模版
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = simpleDateFormat.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 查询该用户今日是否已经排班
        boolean flat = tTeacherRosteringMapper.getTodayRossteringInfo(userId, date);
        if (flat)
            return "用户该日已排班！";

        // 根据id查询教师姓名
        TTeacher teacher = teacherMapper.findTeacherById(userId);
        TTeacherRostering tTeacherRostering = new TTeacherRostering();
        // 设置信息
        String dingId = teacher.getDingId();
        tTeacherRostering.setWorkDate(date);
        tTeacherRostering.setTeacherId(userId);
        tTeacherRostering.setUserid(dingId);
        tTeacherRostering.setTeacherName(teacher.getName());
        tTeacherRostering.setGroupId(group_id);
        tTeacherRostering.setShiftId(shift_id);

        // 新增排班信息
        tTeacherRosteringMapper.insertTTeacherRostering(tTeacherRostering);

        Long workDate = date.getTime();
        String s = RosterUtil.arrangeRoster(group_id, shift_id, workDate, dingId);
        Boolean success = JSONObject.parseObject(s)
                .getBoolean("success");
        if (!success) {
            return "排班错误，请联系管理员！";
        }
        return "排班成功！";
    }

    @Override
    public List<GroupVo> getUserGroupInfo() {
        // 获取登录用户id
        Long userId = SecurityUtils.getUserId();
        // 根据id查询教师信息
        TTeacher teacher = teacherMapper.findTeacherById(userId);
        String userGroup = RosterUtil.getUserGroup(teacher.getDingId());
        String result = JSONObject.parseObject(userGroup)
                .getString("result");
        GroupVo groupVo = JSONObject.parseObject(result, GroupVo.class);
        ArrayList<GroupVo> groupVos = new ArrayList<>();
        groupVos.add(groupVo);
        return groupVos;
    }

    @Override
    public List<RosteringVo> getRosteringList(TTeacherRostering tTeacherRostering) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        String format = simpleDateFormat.format(new Date());
        List<TTeacherRostering> rosteringList = tTeacherRosteringMapper.getRosteringList(tTeacherRostering,format);
        List<RosteringVo> rosteringVos = new ArrayList<>();
        List<Date> collect = rosteringList.stream().map(TTeacherRostering::getWorkDate).collect(Collectors.toList());
        for (Date date : collect) {
            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String workDate = simpleDateFormat.format(date);
            RosteringVo rosteringVo = new RosteringVo();
            rosteringVo.setDate(workDate);
            ArrayList<String> list = new ArrayList<>();
            for (TTeacherRostering Rostering : rosteringList) {
                if(Rostering.getWorkDate().equals(date))
                    list.add(Rostering.getTeacherName());
            }
            rosteringVo.setContent(list);
            rosteringVos.add(rosteringVo);
        }
        System.out.println(rosteringVos);
        return rosteringVos;
    }

    @Override
    public List<String> getTeacherNameList() {
        return teacherMapper.getTeacherNameList();
    }

}
